﻿using AutoMapper;
using Common;
using DB.Mapper;
using DB.Model;
using DB.Model.Input;
using DB.MongoDB;
using Http.Token;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using NoticeCorpWechat.interfaces;
using NoticeCorpWechat.result;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace NoticeWechat.Controllers
{

    public class UserController : ApiController
    {
        IMongoDbHelper<User> _Db;
        ITokenHelper _TokenHelper;
        IAccessTokenHelper _AccessTokenHelper;
        IMemoryCache _cache;
        IMapper _mapper;
        public UserController(IMongoDbHelper<User> mongoDb, ITokenHelper tokenHelper,
            IAccessTokenHelper AccessTokenHelper, IMemoryCache memoryCache, IMapper mapper)
        {
            _Db = mongoDb;
            _TokenHelper = tokenHelper;
            _AccessTokenHelper = AccessTokenHelper;
            _cache = memoryCache;
            _mapper = mapper;
        }

        [HttpPost]
        public async Task<AjaxResult> Register(UserInput userInput)
        {
            return new AjaxResult() { Message = "不开放注册功能", Type = ResultType.Failed };

            if (userInput.Account.IsNullOrEmpty() || userInput.Pwd.IsNullOrEmpty())
            {
                return new AjaxResult() { Message = "账号或密码不为空", Type = ResultType.Failed };
            }
            if (userInput.CorpId.IsNullOrEmpty() || userInput.AgentId.IsNullOrEmpty() || userInput.CorpSecret.IsNullOrEmpty())
            {
                return new AjaxResult() { Message = "企业微信内容不为空", Type = ResultType.Failed };
            }
            var code = _cache.Get(userInput.CodeId);
            if (code == null || userInput.Code != code.ToString())
            { return new AjaxResult() { Message = "验证码不正确,请重新输入", Type = ResultType.Failed }; }

            var one = _Db.AsQueryable().Where(x => x.Account == userInput.Account).FirstOrDefault();
            if (one != null)
            { return new AjaxResult() { Message = "账号已被占用,请更改", Type = ResultType.Failed }; }
            var user = _mapper.Map<User>(userInput);
            user.Pwd = user.Pwd.Sha256();
            user.State = 1;
            user.Times = 5;
            await _Db.Insert(user);
            return new AjaxResult() { Message = "注册成功", Type = ResultType.Success };
        }

        [HttpPost]
        public AjaxResult Login(UserLoginInput user)
        {
            if (user.Account.IsNullOrEmpty() || user.Pwd.IsNullOrEmpty())
            {
                return new AjaxResult() { Message = "账号或密码不为空", Type = ResultType.Failed };
            }
            var code = _cache.Get(user.CodeId);
            if (code == null || user.Code != code.ToString())
            { return new AjaxResult() { Message = "验证码不正确,请重新输入", Type = ResultType.Failed }; }
            var pwd = user.Pwd.Sha256();

            var one = _Db.AsQueryable().Where(x => x.Account == user.Account && x.Pwd == pwd).FirstOrDefault();
            if (one == null)
            {
                return new AjaxResult() { Message = "账号或密码不正确", Type = ResultType.Failed };
            }
            var id = one.Id.ToString();
            var token = _TokenHelper.CreateToken(id, user.Account);

            return new AjaxResult() { Message = "登录成功", Type = ResultType.Success, Data = token };

        }

        [Authorize]
        [HttpGet]
        public async Task<AjaxResult> Get_WechatToken()
        {
            var id = User.Identity.GetUserId();
            if (id.IsNullOrEmpty()) return new AjaxResult() { Type = ResultType.Failed, Message = "请重新登录!" };
            var one = _Db.AsQueryable().Where(x => x.Id == id.ToObjectId()).FirstOrDefault();
            if (one == null) return new AjaxResult() { Type = ResultType.Failed, Message = "请重新登录!" };
            if (DateTime.Now.AddMinutes(20) <= one.Expires_in)
            {
                return new AjaxResult() { Data = one.Access_token };
            }
            var result = _AccessTokenHelper.Get_AccessToken(one.CorpId, one.CorpSecret);
            if (result.IsNullOrEmpty()) { return new AjaxResult() { Type = ResultType.Failed, Message = "获取微信token失败!" }; }
            var res = result.JsonToObject<TokenResult>();
            if (res.errcode == 0)
            {
                one.Expires_in = DateTime.Now.AddSeconds(res.expires_in);
                one.Access_token = res.access_token;
                await _Db.Update(one);
            }
            return new AjaxResult() { Type = ResultType.Success, Data = res.access_token };
        }

        [Authorize]
        [HttpGet]
        public AjaxResult RefreshToken()
        {
            var token = _TokenHelper.RefreshToken(User);
            return new AjaxResult() { Message = "刷新Token成功", Type = ResultType.Success, Data = token };
        }
    }
}
